本篇同步發布於Blog: [解題] LeetCode - 832 Flipping an Image
LeetCode
832 - Flipping an Image
https://leetcode.com/problems/flipping-an-image/
輸入1個二維陣列A,A的列與行的長度相等,求把這二維陣列翻轉的結果。翻轉的定義為先把每一列的值作順序倒轉,再把每個值從0改1、從1改0。
比如範例輸入的
[1,1,0,0],
[1,0,0,1],
[0,1,1,1],
[1,0,1,0]
先做順序倒轉,變成
[0,0,1,1],
[1,0,0,1],
[1,1,1,0],
[0,1,0,1]
再做0改1、1改0,變成
[1,1,0,0],
[0,1,1,0],
[0,0,0,1],
[1,0,1,0]
雙層迴圈,從陣列A的第1列開始循環,利用長度n - i - 1即可計算倒轉的順序索引值。
難度為Easy
#include <iostream>
#include <vector>
using namespace std;
 
class Solution {
public:
    vector<vector<int>> flipAndInvertImage(vector<vector<int>>& A) {
        int n = A.size();
        vector<vector<int>> ans;
 
        for(int i = 0 ;i < n;++i){
            vector<int> row(n);
            for(int j = 0;j < n;++j){
                row[n-j-1] = A[i][j] == 1 ? 0 : 1;
            }
 
            ans.push_back(row);
        }
 
        return ans;
    }
};
 
int main() {
	vector<vector<int>> A;
	vector<int> row1{1,1,0,0};
	vector<int> row2{1,0,0,1};
	vector<int> row3{0,1,1,1};
	vector<int> row4{1,0,1,0};
	A.push_back(row1);
	A.push_back(row2);
	A.push_back(row3);
	A.push_back(row4);
 
	Solution sol;
	vector<vector<int>> ans = sol.flipAndInvertImage(A);
	for(int i = 0 ; i < ans.size();++i){
		for(int j = 0 ; j < ans[i].size();++j){
			cout << " " << ans[i][j];
		}
		cout << endl;
	}
 
	return 0;
}
using System;
					
public class Program
{
	public class Solution {
		public int[][] FlipAndInvertImage(int[][] A) {
			int n = A.Length;
			int[][] ans = new int[n][];
			for(int i = 0 ; i < n;++i){
				ans[i] = new int[n];
			}
			for(int i = 0 ;i < n;++i){
				int[] row = new int[n];
				for(int j = 0;j < n;++j){
					row[n-j-1] = A[i][j] == 1 ? 0 : 1;
				}
				ans[i] = row;
			}
			return ans; 
		}
	}
	
	public static void Main()
	{
		int[][] A =
		{
			new int[] { 1,1,0,0 },
			new int[] { 1,0,0,1 },
			new int[] { 0,1,1,1 },
			new int[] { 1,0,1,0 }
		};
		
		Solution sol = new Solution();
		var ans = sol.FlipAndInvertImage(A);
		
		foreach(var row in ans){
			foreach(int col in row){
				Console.Write(" " + col);
			}
			Console.WriteLine();
		}
		
		Console.Read();
	}
}
https://github.com/u8989332/ProblemSolving/blob/master/LeetCode/C%2B%2B/800-899/832.cpp
https://github.com/u8989332/ProblemSolving/blob/master/LeetCode/C%23/800-899/832.cs